package com.loozb.fork;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

/**
 * 构造一个计算1到200000求和的任务
 * Created by chuan on 2017-9-18.
 */
public class CountTask extends RecursiveTask<Long> {

    private static final int threshold = 10000;
    private long start;
    private long end;

    public CountTask(long start, long end) {
        this.start = start;
        this.end = end;
    }

    @Override
    protected Long compute() {
        long sum = 0;
        int taskNum = 100;
        //每组分10000个执行，如果使用end-start小于10000，则直接循环相加返回
        if((end - start) < threshold) {
            for(long i = start; i <= end; i++) {
                sum += i;
            }
        } else {
            //分成1000个小任务执行
            long step = (start + end) / taskNum;
            ArrayList<CountTask> subTasks = new ArrayList<>();
            long pos = start;
            for(int i = 0; i < taskNum; i++) {
                long lastOne = pos + step;
                if( lastOne > end) lastOne = end;
                CountTask subTask = new CountTask(pos, lastOne);
                pos += step + 1;
                subTasks.add(subTask);
                subTask.fork();
            }

            //全部等待处理结束
            for(CountTask t: subTasks) {
                sum += t.join();
            }
        }
        return sum;
    }

    public static void main(String[] args) {
        ForkJoinPool forkJoinPool = new ForkJoinPool();

        long n1 = System.currentTimeMillis();
        //计算1到200000求和
        CountTask task = new CountTask(0, 30000L);

        ForkJoinTask<Long> result = forkJoinPool.submit(task);

        try {
            long res = result.get();
            System.out.println("sum="+res);
            long n2 = System.currentTimeMillis();
            System.out.println(n2-n1);
        } catch (InterruptedException e) {

        } catch (ExecutionException e) {

        }
//        long n11 = System.currentTimeMillis();
//        long m = 0;
//        for(int i = 0; i <= 100000; i++) {
//            try {
//                Thread.sleep(10);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
//            m += i;
//        }
//        System.out.println(m);
//        long n21 = System.currentTimeMillis();
//        System.out.println(n21-n11);
    }
}
